import { api } from './api';
import { GameInfo, GameState } from '../store/gameSlice';

// 获取所有可用游戏
export const getAvailableGames = async (): Promise<GameInfo[]> => {
  const response = await api.get('/api/games');
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to get games');
  }
  return response.json();
};

// 创建新游戏
export const createGame = async (gameData: {
  name: string;
  maxPlayers: number;
  minBet: number;
}): Promise<GameInfo> => {
  const response = await api.post('/api/games', gameData);
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to create game');
  }
  return response.json();
};

// 加入游戏
export const joinGame = async (gameId: string): Promise<GameState> => {
  const response = await api.post(`/api/games/${gameId}/join`, {});
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to join game');
  }
  return response.json();
};

// 离开游戏
export const leaveGame = async (gameId: string): Promise<void> => {
  const response = await api.post(`/api/games/${gameId}/leave`, {});
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to leave game');
  }
};

// 获取游戏状态
export const getGameState = async (gameId: string): Promise<GameState> => {
  const response = await api.get(`/api/games/${gameId}`);
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to get game state');
  }
  return response.json();
};

// 执行游戏动作（下注、跟注、加注、弃牌等）
export const makeGameAction = async (
  gameId: string,
  action: {
    type: 'check' | 'call' | 'raise' | 'fold' | 'all-in';
    amount?: number;
    playerId?: number; // 添加玩家ID，用于无需认证的游戏
  }
): Promise<GameState> => {
  const response = await api.post(`/api/games/${gameId}/action`, action);
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to make action');
  }
  return response.json();
};

// 开始游戏
export const startGame = async (gameId: string): Promise<GameState> => {
  const response = await api.post(`/api/games/${gameId}/start`, {});
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Failed to start game');
  }
  return response.json();
};

// 默认导出，包含所有游戏服务函数
const gameService = {
  getAvailableGames,
  createGame,
  joinGame,
  leaveGame,
  getGameState,
  makeGameAction,
  startGame,
};

export default gameService;